package fido.torrentsite;


import fido.DefaultTorrentImpl;
import fido.FidoCommonUtils;
import fido.Torrent;
import org.mymediadb.api.mmdb.model.Movie;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

public final class BitHDTV extends CookiedTorrentSite {

    public BitHDTV() {
        super();
    }


    protected String getRegex() {
        return "<td class=detail align=center><p><a href='(http://www.bit-hdtv.com/download.php/.*?)'>.*?<a title=\\\"(.*?)\\\".*?href=\\\"(.*?)\\\">.*?<td class=detail align=center>.*?<td class=detail align=center>.*?<td class=detail align=center>(.*?)</td>.*?<span class=\\\"white\\\">(.*?)</span>";
    }

    protected String getURL() {
        return "http://www.bit-hdtv.com/";
    }

    protected String getSearchURL() {
        return "http://www.bit-hdtv.com/torrents.php?search={0}&cat=7&sort=6&type=desc";
    }

    protected boolean isLoggedIn(String loginPageUrl) {
        return !(loginPageUrl.equals("") || loginPageUrl.contains("takelogin.php"));
    }

    protected String getTextEncoding() {
        return "ISO-8859-1";
    }


    protected List<CookieVariable> getCookieVariables() {
        List<CookieVariable> cookieVariables = new ArrayList<CookieVariable>();
        cookieVariables.add(new CookieVariable("h_su", "user id"));
        cookieVariables.add(new CookieVariable("h_sp", "passkey"));
        cookieVariables.add(new CookieVariable("h_sl", "passkey2"));
        return cookieVariables;
    }

    protected Torrent getTorrentFromMatcherData(Matcher matcher, Movie movie) {
        fido.Torrent torrent;
        int torrentCounter = 0;

        while (matcher.find()) {
            torrentCounter++;
            torrent = new DefaultTorrentImpl();
            torrent.setTorrentUrl(matcher.group(1));
            torrent.setName(matcher.group(2));
            torrent.setDetailsPageUrl("http://www.bit-hdtv.com/" + matcher.group(3));

            torrent.setSeeders(Integer.parseInt(matcher.group(4).replaceAll(",|\\.", "")));
            torrent.setLeechers(Integer.parseInt(matcher.group(5).replaceAll(",|\\.", "")));

            //Adding cookie so we can access the page
            torrent.setCookie(getCookieString());
            if (FidoCommonUtils.doesImdbIdExistsInTorrentDetails(torrent, movie.getImdbId())) {

                LOG.debug("Found torrent IMDBId in details page");
                return torrent;
            }
            LOG.debug("Found torrent:" + torrent.getName() + " but imdbID |" + movie.getImdbId() + "| didn't match");
        }

        if (torrentCounter == 0) {
            LOG.debug("No torrents found at all, There were no results on the search page?");
        } else {
            LOG.debug("Found " + torrentCounter + " torrents matching search name - but not ImdbID");
        }
        return null;
    }


}
